#include "MapState.h"
#include <stdlib.h>

MapState::MapState()
{

}

void MapState::Load()
{
    hud = IMG_Load("HUD.png");
    aluno = new Aluno(731, 10, "aluno.png");
    inmanager = InputManager::getInstance();
    professor = new Professor(495,190,"professor.png");
    counter = new TimeCounter();
    tempo = true;
    teste = false;

    text = new Text("liberation_sans.ttf"," ", 10.0, 10.0, TTF_STYLE_NORMAL , 0, 0, 0, 32);
    text2 = new Text("liberation_sans.ttf"," ", 10.0, 42.0, TTF_STYLE_NORMAL , 0, 0, 0, 32);

    Tileset *tileset = new Tileset(TILESIZE);
	tileset->addBMPTile( "tileYellow.bmp" );
	tileset->addBMPTile( "grass2.bmp" );
	tileset->addBMPTile( "grass3.bmp" );
	tileset->addBMPTile( "grass4.bmp" );
	tileset->addBMPTile( "tileBrown.bmp" );
	tileset->addBMPTile( "tileBrown.bmp" );
	tileset->addBMPTile( "tileBrown.bmp" );
	tileset->addBMPTile( "tileBrown.bmp" );
	tileset->addBMPTile( "tileBrown.bmp" );

	tilemap = new Tilemap(tileset, MAPWIDTH, MAPHEIGHT);

    FILE *arqMap = fopen("mapa.txt", "r");
    x = 0;
    y = 0;
    c = getc(arqMap);
    while(c != EOF)
    {
        if(c == '\n')
        {
            x = 0;
            y++;
        }
        else
        {
            tilemap->tileMatrix[x][y] = c - 48;
            x++;
        }
        c = getc(arqMap);
    }
    dstrect.x = 0;
    dstrect.y = 0;
}

void MapState::Unload()
{
    delete(counter);
    delete(tilemap);
}

int MapState::Update(int dt)
{
    quit = inmanager->Update();
    aluno->Update(dt);
    professor->Update(dt);
    teste = professor->inRange(aluno->x,aluno->y);

    if(teste && tempo){
        counter->Start();
        aluno->life-= 1;
        tempo = false;
    }
    itoa(aluno->life,buffer,10);
    text->changeText(buffer);
    if((counter->GetTime() > 1000) && (counter->GetTime() < 2000)){
        tempo = true;
        counter->Stop();
    }

    if(inmanager->isKeyPressed(SDLK_ESCAPE) || quit)
        return -1;

    return 0;
}

void MapState::Render(SDL_Surface *screen)
{
    SDL_Rect rectangle;
    rectangle.x = 768;
    rectangle.y = 0;
    SDL_FillRect(screen, 0, SDL_MapRGB(screen->format, 0, 0, 0));
    SDL_BlitSurface(hud, 0, screen, &rectangle);

    tilemap->render(screen);
    text->Render(screen);
    text2->Render(screen);
    aluno->Render(screen);
    professor->Render(screen);

}

